<template>
  <div class="new-page" :style="`min-height: ${pageMinHeight}px`">
    <div class="table_box">
      <div class="table_header">
        <div class="search">
          <a-input-search
            placeholder="名称"
            style="width: 200px"
            v-model="searchData.name"
            @search="onSearch"
          />
        </div>
        <div class="btn">
          <a-button type="primary" @click="goadd"> 新增 </a-button>
        </div>
      </div>
      <div class="table_content">
        <a-table
          :columns="columns"
          :rowKey="(record) => record.id"
          :data-source="data"
          :pagination="pagination"
          :show-total="total => `Total ${total} items`"
          :loading="loading"
          @change="handleTableChange"
        >
          <div slot="roles" slot-scope="text, record">
            <span>{{record.roles.map(e=>e.name).join('')}}</span>
          </div>
          <div slot="operation" slot-scope="text, record">
              <a-button
                type="link"
                style="color: #1890ff"
                @click="goInfo(record)"
                ghost
              >
                电站信息
              </a-button>
            <a-button
              type="link"
              style="color: #1890ff"
              @click="goupdata(record)"
              ghost
            >
              编辑
            </a-button>
            <a-button type="link" style="color: red" @click="delData(record.id)" ghost> 删除 </a-button>
          </div>
        </a-table>
      </div>
      <a-modal v-model="visible" title="站点信息" on-ok="handleOk" width="60%">
          <template slot="footer">
              <a-button key="submit" type="primary" @click="onSubmit">
                保存
              </a-button>
              <a-button key="back" @click="visible=false">
                  关闭
              </a-button>
          </template>
          <div class="form_box">
              <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
                style="max-width: 700px"
              >
              <a-form-model-item label="所属企业" prop="enterprise_id">
                <a-select
                  v-model="enterprisesName"
                  show-search
                  placeholder="选择企业"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  @search="handleSearch($event,'enterprises')"
                  @change="handleChange"
                >
                <a-select-option v-for="d in enterprises" :key="d.id">
                  {{ d.name }}
                </a-select-option>
                </a-select>
              </a-form-model-item>
                <a-form-model-item ref="name" label="站点名称" prop="name">
                  <a-input
                    v-model="form.name"
                    placeholder="请输入站点名称"
                    @blur="
                      () => {
                        $refs.name.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
                <a-form-model-item ref="director" label="负责人" prop="director">
                  <a-input
                    v-model="form.director"
                    placeholder="请输入负责人名称"
                    @blur="
                      () => {
                        $refs.director.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
                <a-form-model-item ref="mobile" label="负责人电话" prop="mobile">
                  <a-input
                    v-model="form.mobile"
                    placeholder="请输入负责人电话"
                    @blur="
                      () => {
                        $refs.mobile.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
                <a-form-model-item ref="mobile" label="站点区域" prop="zone">
                  <a-cascader class="selectAdderCascader" :defaultValue="defaultValue" :placeholder="form.zone|| '请选择站点区域'" :load-data="loadData" :options="options" change-on-select @change="onChange" />
                </a-form-model-item>
                <a-form-model-item ref="address" label="站点地址" prop="address">
                  <a-input
                    v-model="form.address"
                    placeholder="请输入站点地址"
                    @blur="
                      () => {
                        $refs.address.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
            </a-form-model>
          </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { gets,del,get,updata,add} from "@/services";
import { getSearchCriteria } from "@/utils/util"

export default {
  name: "Demo",
  data() {
    return {
      columns: [
        {
          title: "站点名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "所属企业",
          key: "enterprise",
          dataIndex: "enterprise.name",
        },
        {
          title: "站点地址",
          key: "address",
          dataIndex: "address",
        },
        {
          title: "站点负责人",
          key: "director",
          dataIndex: "director",
        },
        {
          title: "站点电话",
          key: "mobile",
          dataIndex: "mobile",
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: "",
      enterprisesName:'',
      form: {},
      options:[],
      enterprises:[],
      pagination: {
        pageSize: 10,
      },
      searchData:{
        name:''
      },
      loading: false,
      data: [],
      visible:false,
      defaultValue:[],
      rules: {
        enterprise_id:[
          {
            required: true,
            message: "请选择企业",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入站点名称",
            trigger: "blur",
          },
        ],
        director: [
          {
            required: true,
            message: "请输入负责人名称",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入负责人电话",
            trigger: "blur",
          },
        ],
        zone: [
          {
            required: true,
            message: "请选择地区",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入地址",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("setting", ["pageMinHeight"]),
  },
  created() {
    this.fetch({limit:10})
    this.handleSearch('','enterprises')
    gets({},'region').then(({data})=>{
        if(data.code==20000){
            this.options = data.data.map(e=>{
                return {
                      value: e,
                      label: e,
                      l: 1,
                      isLeaf: false,
                }
            })
        }
    })
  },
  methods: {
      goInfo(e){
          this.$router.push(`/user/stationsInfo?id=`+e.id);
      },
      onSubmit(){
          let _this = this;
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
                let fun =_this.form.id?updata:add
              fun(_this.form,'esStations').then(({ data }) => {
                if (data.code == 20000) {
                  _this.resetForm();
                } else {
                  _this.$message.error("修改失败");
                }
              });
            } else {
              console.log("error submit!!");
              return false;
            }
          });
      },
      resetForm(){
          this.visible= false
          this.fetch({page: this.pagination.current || 1,limit: this.pagination.pageSize||10})
      },
      onChange(e){
          console.log(e);
          this.form.zone = e.join('')
      },
      handleChange(value) {
        this.form.enterprise_id = value
      },
      handleSearch(txt,thisName){
        console.log(txt,thisName);
        let _this = this
        let search = {
          search:txt,
          searchFields:'name:like'
        }
        gets(search,thisName).then(({data})=>{
          if(data.code==20000){
            _this[thisName] = data.data.data
          }
        })
      },
    loadData(selectedOptions) {
        console.log(222,selectedOptions);
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        let rdata = {}
        if(targetOption.l==1){
            rdata.province = targetOption.value
        }
        if(targetOption.l==2){
            rdata.province = selectedOptions[selectedOptions.length - 2].value
            rdata.city = targetOption.value
        }
        gets(rdata,'region').then(({data})=>{
            if(data.code==20000){
                targetOption.children = data.data.map(e=>{
                    let info = {
                          value: e,
                          label: e,
                          l: targetOption.l+1,
                    }
                    if(targetOption.l!=2){
                        info.isLeaf=false
                    }
                    return info
                })
                targetOption.loading = false;
                this.options = [...this.options];
            }
        })
      },
    handleTableChange(pagination, filters) {
      console.log(pagination,filters);
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.fetch({
        page: pagination.current,
        limit: pagination.pageSize,
        ...filters,
      });
    },
    fetch(params = {}) {
      this.loading = true;
      gets({
        ...params,
        ...(getSearchCriteria(this.searchData))
      },'esStations').then(({ data }) => {
        if (data.code == 20000) {
        let res = data.data;
        this.data = res.data;
        this.pagination.total = res.total
        this.pagination = {...this.pagination}
      }
        this.loading = false;
      });
    },
    delData(id) {
      let _this = this
      this.$confirm({
        title: "是否确定删除这条数据?",
        content: "数据删除后将无法恢复",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          del(id,'users').then(({ data }) => {
            if (data.code == 20000) {
              _this.$message.success("删除成功");
              console.log(_this.pagination);
              let i = 0;
              if (_this.data.length == 1) {
                i = 1;
              }
              _this.fetch({ limit: 10, page: _this.pagination.current - i });
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },
    goupdata(row) {
        this.form={...row}
        this.defaultValue = []
        this.enterprisesName = row.enterprise.name
      this.visible = true
    },
    goadd(){
        this.form={}
        this.enterprisesName = ''
        this.defaultValue = []
        this.visible = true
    },
    onSearch() {
      this.fetch({limit:10})
    },
  },
};
</script>

<style scoped lang="less">
.new-page {
  height: 100%;
  background-color: @base-bg-color;
  text-align: center;
  border-radius: 4px;
  .table_box {
    padding: 16px 23px;
    .table_header {
      display: flex;
      justify-content: space-between;
      padding-bottom: 24px;
    }
  }
}
</style>